<template>
	<view class="page">
		<view class="list" v-if="comit">
			<view class="item">
				<text class="key">审批人选择</text>
				<uni-icons type="compose" size="20"></uni-icons>
				<picker :value="approvalIndex" :range="approvalArrayName" @change="approvalChange">{{approvalArrayName[approvalIndex]==undefined?"请选择":approvalArrayName[approvalIndex]}}
				</picker>
			</view>
			<view class="item">
				<text class="key">姓名</text>
				<text class="value">{{name}}</text>
			</view>
			<view class="item">
				<text class="key">联系号码</text>
				<text class="value">{{account}}</text>
			</view>
			<view class="item">
				<text class="key">邮箱</text>
				<text class="value">{{email}}</text>
			</view>
			<view class="item">
				<text class="key">当前所在组织</text>
				<text class="value">{{organization}}</text>
			</view>
			<view class="item">
				<text class="key">当前任职岗位</text>
				<text class="value">{{post}}</text>
			</view>
			<view class="item" @tap="editOutReason">
				<text class="key">离职原因</text>
				<uni-icons type="compose" size="20"></uni-icons>
				<text class="value">{{outReason}}</text>
			</view>
			<uni-popup ref="popupOutReason" type="dialog">
				<uni-popup-dialog mode="input" title="离职原因" :value="outReason" placeholder="请简单说明一下申请理由,不超过30字!" @confirm="finishOutReason">
				</uni-popup-dialog>
			</uni-popup>
			<view class="item">
				<text class="key">申请日期</text>
				<text class="value">{{createTime}}</text>
			</view>
		</view>
		<uni-section title="请选择离职证明书面版(限1张)" type="line" v-if="comit">
			<view class="example-body" >
				<uni-file-picker
					file-mediatype="image"
					disable-preview
					:del-icon="false"
					mode="grid"
					ref="file"
					file-extname="png,jpg"
					:limit="1"
					:auto-upload="false"
					:source-type=source
					@select="getPhotoPath"
				></uni-file-picker>
			</view>
		</uni-section>
		<uni-steps :options="stepList" :active-icon="icon" :active-color="color" :active="active" direction="column" v-if="step" />
		<button class="save-btn" @tap="save" v-if="comit">提 交</button>
		<button class="save-btn" @tap="undo" v-if="revoke">撤 销</button>
		<button class="save-btn" @tap="remit" v-if="over">再次提交</button>
	</view>
</template>

<script>
	import uniPopup from '@/components/uni-popup/uni-popup.vue';
	import uniPopupMessage from '@/components/uni-popup/uni-popup-message.vue';
	import uniPopupDialog from '@/components/uni-popup/uni-popup-dialog.vue';
	import uniFilePicker from '@/components/uni-file-picker/uni-file-picker.vue';
	import uniSection from '@/components/uni-section/uni-section.vue';
	import uniSteps from '@/components/uni-steps/uni-steps.vue';
	export default {
		components: {
			uniPopup,
			uniPopupMessage,
			uniPopupDialog,
			uniFilePicker,
			uniSection,
			uniSteps
		},
		data() {
			return {
				//当前审批
				approvalId:0,
				//当前离职id
				outId:0,
				//审批人选择
				approvalArrayName:[],
				approvalArrayId:[],
				approvalUserId:-1,
				approvalIndex:0,
				//姓名
				name:'',
				//联系号码
				account:'',
				//邮箱
				email:'',
				// 所在组织
				organization:'',
				organizationId:0,
				// 所在岗位
				post:'',
				postId:0,
				//申请理由
				outReason:'',
				// 当前日期
				nowDate:'',
				// 当前时间
				nowTime:'',
				// 登记日期
				createTime:'',
				//证明照片路径
				tempFilePaths:[],
				//证明文件的路径
				certificate:'',
				// 从本地相册中选择
				source:['album'],
				// 提交状态
				comit:true,
				// 审核状态
				// 撤销状态
				revoke:false,
				// 审核步骤
				step:false,
				// 激活步骤
				active: 0,
				// 步骤线
				stepList: [],
				// 步骤线颜色
				color:"#007AFF",
				// 步骤前icon
				icon:"smallcircle-filled",
				// 完成状态
				over:false
			}
		},
		onLoad:function(){
			let that = this;
			let now = new Date();
			let year = now.getFullYear();
			let month = now.getMonth() + 1;
			month = month < 10 ? '0' + month : month;
			let date = now.getDate();
			date = date < 10 ? '0' + date : date;
			let yyyymmdd = year + '/' + month + '/' + date
			let yyyy_mm_dd = year + '-' + month + '-' + date
			that.nowDate = yyyymmdd;
			that.nowTime = yyyy_mm_dd;
			// 加载登记时间
			that.loadCreateTime(that);
		},
		onShow: function() {
			let that = this;
			//加载初始化用户相关信息
			that.loadInitUser(that);
			// 判断当前页面是否为审批状态
			that.curApproval(that);
		},
		methods: {
			//判断当前页面是否为审批状态
			curApproval:function(ref){
				ref.ajax(ref.url.curApproval,'POST',{
					approvalType:'out'
				},function(resp){
					let data = resp.data;
					//如果是
					if(data.curApproval.length>0){
						//当前审批的数据
						let cur = data.curApproval[0];
						//提交内容不可见，提交按钮不可见
						ref.comit = false;
						//步骤条可见
						ref.step = true;
						ref.active = cur.approvalStatus;
						//当前审核id
						ref.approvalId = cur.id;
						//待审核时显示
						if(cur.approvalStatus==1){
							ref.stepList = [
								{title: '已提交',desc: '提交日期:'+ref.formatDataTime(cur.applyTime)}, 
								{title: '待审核',desc: '审核中，请耐心等待……'},
								]
								ref.revoke = true
						}
						//已审核（通过时显示）
						if(cur.approvalStatus==2){
							ref.color="#55aa00"
							ref.revoke = false
							ref.over = true
							ref.stepList = [
								{title: '已提交',desc: '提交日期:'+ref.formatDataTime(cur.applyTime)}, 
								{title: '待审核',desc: '审核日期:'+ref.formatDataTime(cur.applyTime)},
								{title: '通过',desc: '本次提交已通过'}
								]
							ref.ajax(ref.url.updateUserDimission,'PUT',{
								id:null
							},function(resp){
								
							})
						}
						//已审核（未通过时显示）
						if(cur.approvalStatus==3){
							ref.revoke = false
							ref.over = true
							ref.stepList = [
								{title: '已提交',desc: '提交日期:'+ref.formatDataTime(cur.applyTime)}, 
								{title: '待审核',desc: '审核日期:'+ref.formatDataTime(cur.applyTime)},
								{title: '未通过',desc: '未通过理由:'+cur.approvalReason}
								]
							ref.color="#ff0000"
						}
					}
				});
			},
			//加载审批人数据
			loadArrovalData(ref){
				ref.ajax(ref.url.getAdmins,'POST',{
					id:ref.organizationId
				},function(resp){
					let data = resp.data.data;
					let arrName = [];
					let arrId=[];
					for(let one of data){
						ref.approvalArrayId.push(one.id);
						ref.approvalArrayName.push(one.name);
					}
					ref.approvalUserId = ref.approvalArrayId[0];
					ref.approvalIndex = ref.approvalArrayId.indexOf(ref.approvalUserId)
					uni.setStorageSync("dimissio-approvalUserId",ref.approvalUserId);
				});
			},
			//选择审批人
			approvalChange: function(e) {
				let that = this;
				that.approvalIndex = e.detail.value;
				uni.setStorageSync("dimission-approvalUserId",that.approvalArrayId[that.approvalIndex])
				that.approvalUserId = uni.getStorageSync("dimission-approvalUserId");
			},
			//加载初始化用户信息
			loadInitUser:function(ref){
					ref.ajax(ref.url.getuserinfo, "POST", null, function(resp) {
					let data = resp.data;
					let user = data.userinfo.user;
					let roles = data.userinfo.roles;
					let message = "未填写";
					if(!user.isRegistration){
						uni.showToast({
							title:"未登记",
							icon:'error'
						});
						setTimeout(function(){
							uni.switchTab({
								url:'../index/index'
							})
						},1000)
					}
					// 姓名
					if(user.name==null){
						ref.name = "新员工"
					}else{
						ref.name = user.name;
					}
					// 当前所在组织
					if(user.organization==null){
						ref.organization = message
					}else{
						ref.organization = user.organization.name
						ref.organizationId = user.organization.id;
						//加载审批人数据
						ref.loadArrovalData(ref);
					}
					//当前所在岗位
					if(user.job==null){
						ref.post = message
					}else{
						ref.post = user.job.name
						ref.postId = user.job.id
					}
					// 账号
					if(user.account==null){
						ref.account = message
					}else{
						ref.account = user.account
					}
					// 电子邮件
					if(user.email==null){
						ref.email = message
					}else{
						ref.email = user.email
					}
				});
				if(uni.getStorageSync('dimission-reason').length>0){
					ref.reason = uni.getStorageSync('dimission-reason');
				}
			},
			//编辑离职说明
			editOutReason:function(){
				this.$refs.popupOutReason.open();
			},
			//完成离职说明编辑
			finishOutReason:function(done,value){
				let that = this;
				if(value.length>=30){
					uni.showToast({
						title:"字数太多",
						icon:'error'
					});
					return;
				}else{
					uni.setStorageSync("dimission-reason",value)
					that.outReason = uni.getStorageSync("dimission-reason");
				}
				done();
			},
			//加载登记日期
			loadCreateTime(ref){
				let now = new Date();
				// 获取小时、分钟和秒数，并进行格式化
				let hours = now.getHours();
				hours = hours < 10 ? '0' + hours : hours; // 对于24小时制不需要额外处理
				let minutes = now.getMinutes();
				minutes = minutes < 10 ? '0' + minutes : minutes;
				let seconds = now.getSeconds();
				seconds = seconds < 10 ? '0' + seconds : seconds;
				ref.createTime = ref.nowTime+' '+hours+':'+minutes+':'+ seconds;
			},
			// 获取照片路径
			getPhotoPath(e){
				let that = this;
				that.tempFilePaths = e.tempFilePaths;
			},
			//提交申请
			save(){
				let that = this;
				if(
					//选择的审批人的id是否选择
					that.approvalUserId<=0 ||
					//离职说明是否填写
					that.outReason.length<=0 ||
					//离职材料是否存在
					that.tempFilePaths.length<=0
				){
					uni.showToast({
						icon: 'error',
						title: '请填写完整相关内容',
					});
				}else{
					uni.showModal({
						title: '提示',
						content: '是否提交员工离职信息申请',
						success: function(e) {
							if(e.confirm){
								let curApprovalUserId='';
								if(typeof(uni.getStorageSync('dimission-approvalUserId'))!='number'){
									curApprovalUserId = that.approvalUserId
								}else{
									curApprovalUserId = uni.getStorageSync('dimission-approvalUserId')
								}
								//上传图片证明并获取url路径
								uni.uploadFile({
									url:that.url.uploadCosFile,
									filePath:that.tempFilePaths[0],
									name:"files",
									header:{
										token:uni.getStorageSync("token")
									},
									formData:{
										type:'out'
									},
									success:(uploadFileRes) => {
										let data = JSON.parse(uploadFileRes.data);
										if(data.result.urls.length>0){
											that.certificate = data.result.urls[0];
											uni.setStorageSync("dimission-certificate",data.result.urls[0]);
										}
									}
								});
								//提交一条相关数据到离职记录
								that.ajax(that.url.setDimission,'POST',{
									reason: that.outReason,
									resources: uni.getStorageSync("dimission-certificate")
								},function(resp){
									let data = resp.data
									if(data.code===20000){
										that.outId = data.id;
										//提交一条审批信息到后端审批者界面审批
										that.ajax(that.url.applyApproval,'POST',{
											approvalId:curApprovalUserId,
											applyReason:that.reason,
											certificate:uni.getStorageSync("dimission-certificate"),
											approvalType:"out"
										},function(resp){
											let data = resp.data;
											if(data.code === 20000){
												let data = resp.data;
												//激发为待审核状态（第一次提交时或重新提交时）
												if(data.code===20000){
													//提交内容不可见，提交按钮不可见
													that.comit = false
													//撤销按钮可用
													that.revoke = true
													//步骤条可用
													that.step = true
													//获取当前的审批id
													that.approvalId = data.approvalInfo.id;
													//待审核状态
													that.active = data.approvalInfo.approvalStatus;
													that.stepList = [
														{title: '已提交',desc: '提交日期:'+that.formatDataTime(data.approvalInfo.applyTime)}, 
														{title: '待审核',desc: '审核中，请耐心等待……'},
														]
												}
											}
										});
									}
								});
							}
						}
					});
				}
			},
			//撤销申请
			undo:function(){
				let that = this;
				uni.showModal({
					title: '提示',
					content: '是否确认撤销登记信息',
					success: function(e) {
						if (e.confirm) {
							let form={
								id:that.approvalId,
								cutStatus:1
							}
							that.ajax(that.url.setCut,'POST',form,function(resp){
								let data = resp.data;
								if(data.code===20000){
									uni.showToast({
										icon: 'success',
										title: data.msg,
									});
									//撤销按钮不可见
									that.revoke = false;
									//步骤条不可见
									that.step = false;
									//提交内容和提交按钮可见
									that.comit = true;
									//恢复步骤条颜色
									that.color = "#007AFF";
								}
							})
						}
					}
				});
			},
			//再次提交
			remit(){
				let that = this;
				uni.showModal({
					title: '提示',
					content: '是否确认再次提交信息',
					success: function(e) {
						if (e.confirm) {
							let form={
								id:that.approvalId,
								cutStatus:1
							}
							that.ajax(that.url.setCut,'POST',form,function(resp){
								let data = resp.data;
								if(data.code===20000){
									uni.showToast({
										icon: 'success',
										title: '再次提交',
									});
									//重新提交按钮不可见
									that.over = false;
									//步骤条不可见
									that.step = false;
									//提交内容和提交按钮可见
									that.comit = true;
									//恢复颜色
									that.color = "#007AFF";
								}
							});
						}
					}
				});
			}
		}
	}
</script>

<style lang="less">
@import url('dimission.less');
</style>
